<style lang="scss">
.step-div{
  border-radius: 8px;
  margin-bottom:40px;
  background: #f5f7fa;
  padding:0 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .step-div-list{
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  .step-item{
    display: flex;
    align-items: center;
    justify-content: flex-start;
    height:110px;
  }
  .step-item-name{
    padding:0 20px;
    color:#c0c4cc;
    position: relative;
    text-align: center;
    line-height: 20px;
    cursor: pointer;
    font-size:12px;
    white-space:nowrap;
  }
  .step-item-info{
    background: #fff;
    border-radius: 10px;
    padding:10px;
    width:660px;
    height:100px;
    margin-right:10px;
    .info-row{
      display: flex;
      justify-content: flex-start;
      align-items: center;
      height:50%;
      .info-name{
        font-size:12px;
        width:70px;
      }
      .info-div{
        flex:1
      }
    }
  }

}
</style>
<template>
  <!--新增/编辑跟进-->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :title="title2"
      :beforeClose="handleClose2"
      :visible.sync="dialogVisible2"
      width="1100px">
      <el-form :model="trackingForm" size="mini" label-width="110px" :rules="rules" ref="trackingForm">
        <div class="step-div">
          <div v-for="(item,index) in topStepList" :key="index" class="step-div-list"  @click="showGj(item)">
            <div class="step-item" >
              <div class="step-item-name" :style="{'color':item.type == 0 ? '#c0c4cc' : item.type == 1 ? 'rgb(255,153,0)' : item.type == 2 ? 'rgb(0,128,0)'  : item.type == 3 ? '#409eff' : '#c0c4cc'}">
                <div>
                  <i class="el-icon-edit" style="font-size: 16px" v-if="item.type == 3"></i>
                  <i class="el-icon-time" style="font-size: 16px" v-else-if="item.type == 0"></i>
                  <i class="el-icon-circle-check" style="font-size: 16px" v-else></i>
                </div>
                <div>{{ item.stepName }}</div>
              </div>
              <div class="step-item-info" v-if="item.type == 3">
                <div class="info-row">
                  <div class="info-name">跟进时间：</div>
                  <div class="info-div">
                    <div id="main" style="height:80px;margin-top:30px"></div>
                  </div>
                </div>
                <div class="info-row" style="margin-top:15px">
                  <div class="info-name">跟进目的：</div>
                  <div class="info-div">
                    <div class="target-div">
                      <div class="target-list">
                        <div class="target-item" v-for="(item,index) in topPurposeList" :key="index" :style="{'background':item.isTrue ? '#67c23a' : 'rgb(192,196,204)'}">{{ index+1 }}</div>
                      </div>
                      <div class="target-line"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="index < topStepList.length-1">
              <i class="el-icon-arrow-right" style="color:#c0c4cc;"></i>
            </div>
          </div>
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户名称：" >
              {{trackingForm.customerName}}
            </el-form-item>
            <!--            <el-form-item label="客户名称：" v-else prop="customerId">-->
            <!--              <el-select-->
            <!--                @change="changeCustomer"-->
            <!--                clearable-->
            <!--                v-model="trackingForm.customerId"-->
            <!--                filterable-->
            <!--                remote-->
            <!--                reserve-keyword-->
            <!--                placeholder="请输入关键词"-->
            <!--                :remote-method="querySearch">-->
            <!--                <el-option-->
            <!--                  v-for="item in querySearchList"-->
            <!--                  :key="item.customerId"-->
            <!--                  :label="item.customerName"-->
            <!--                  :value="item.customerId">-->
            <!--                </el-option>-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
          </el-col>
          <el-col :span="16">
            <el-form-item label="联系人：" prop="contactId">
              <el-select  v-model="trackingForm.contactId"  placeholder="请选择联系人" @change="changeContactId" style="width:150px;">
                <el-option v-for="item in contactList"  :key="item.contactId" :label="item.contactName" :value="item.contactId"></el-option>
              </el-select>
              <el-button type="text" style="margin-left:10px" @click="showContact('add','')" v-if="popType == 'add'">新增</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="跟进方式：" prop="trackingTypeId">
              <el-select :disabled="popType=='edit'" v-model="trackingForm.trackingTypeId" placeholder="请选择" clearable @change="changeTmId">
                <el-option v-for="item in trackingMethodList" :key="item.trackingMethod" :disabled="item.disabled"  :value="item.tmId" :label="item.trackingMethod"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="沟通方式：" prop="trackingMethodId">
              <el-select :disabled="popType=='edit'" v-model="trackingForm.trackingMethodId" placeholder="请选择" clearable @change="changetrackingMethodId">
                <el-option v-for="item in interactList"  :value="item.interactId" :label="item.interactType" :key="item.cddId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="跟进目的：" prop="trackingPurposeId">
              <el-select  v-model="trackingForm.trackingPurposeId" placeholder="请选择" clearable @change="changePurposeId">
                <el-option v-for="item in purposeList"  :value="item.purposeId" :label="item.purposeTitle" :key="item.purposeId"></el-option>
                <el-option label="公司破产或已关闭" :value="-1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="客户产品信息：">
              {{goodsLineNamesNew}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="目的说明：">
          {{introduce}}
        </el-form-item>
        <el-form-item label="跟进内容：" prop="trackingContent">
          <el-input v-model="trackingForm.trackingContent" :autosize="{ minRows: 2, maxRows: 6}" type="textarea" :rows="2"></el-input>
        </el-form-item>

        <el-form-item label="目的是否完成：" prop="isInvalid">
          <el-radio-group v-model="trackingForm.isInvalid">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="附件：" >
         <div v-if="trackingForm.trackingTypeId==2">
           <div
            style="width:90px;height:120px;margin-bottom:10px;margin-right:10px;vertical-align: middle;position: relative;display:inline-block"
            v-for="(item,index) in trackingForm.trackingPics"
            :key="index">
            <el-image
              style="width:100%;height:100%;object-fit:contain;"
              :src="item"
              :preview-src-list="Array(item)">
            </el-image>
          </div>
         </div>
         <div v-else>
            <div v-if="trackingForm.trackingPics.length>0">
              <div v-for="(item,index) in trackingForm.trackingPics" :key="index" style="margin-bottom: 10px;">
                <el-input :value="item" readonly style="width: 500px;"></el-input>
                <i class="el-icon-delete-solid" style="cursor: pointer;color:red;font-size:18px;" @click="delImg(index)"></i>
              </div>
            </div>
            <el-upload
              v-if="trackingForm.trackingPics.length<9"
              action="https://upload.qiniup.com"
              drag
              :data="uploadToken"
              :show-file-list="false"
              :http-request="function (upload) { return sliderRequest(upload) }">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/></div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="下次跟进时间：" prop="nextTrackingTime">
          <el-date-picker
            v-model="trackingForm.nextTrackingTime"
            align="right"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="备注：">-->
<!--          <el-input v-model="trackingForm.trackingRemark"  :autosize="{ minRows: 2, maxRows: 6}" type="textarea" :rows="2"></el-input>-->
<!--        </el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增联系人 -->
    <addContacts ref="addContacts" @update="getContactListData('add')"></addContacts>
    <gjzy ref="gjzy"></gjzy>
  </div>

</template>
<script>
import axios from 'axios'
import { getQiniuToken,getContactList,getCustomerOption } from '@/api/partner'
import {addOrUpdateTracking,customerStepList,customerStepDetail} from '@/api/company'
import { getPurposeListAPI,getTrackingMethodListAPI,getInteractListAPI } from "@/api/fms.js";
import {validatePhone} from '@/utils/validate';
import {formatDate} from '@/utils/date';
import gjzy from './gjzy'
import jt from '@/assets/images/jt.png'
import addContacts from '@/views/cms/components/addContacts.vue'
import store from '@/store'
import { mapGetters } from 'vuex'



const defaultTrackingForm = {

  customerId:'',
  contactId:'',
  trackingTypeId:'',
  trackingTypeValue:'',
  userId:'',
  trackingContent:'',
  trackingPics:[],
  nextTrackingTime:'',
  trackingRemark:'',
  isInvalid:null,
  stepId:'',
  stepName:'',
  trackingMethodId:'',
  trackingMethodValue:'',
  trackingPurposeId:'',
  trackingPurposeValue:'',
  goodsLineIds:'',
  goodsLineNames:'',
  customerName:'',
  trackingId:0,
};

const defaultLxrListQuery={
  cglId:[],
  "pageNum" : 1,
  "pageSize" : 10
};

export default {
  name: "index",
  data(){
    return {
      dialogVisible2:false,
      title2:'',
      btnLoading2:false,
      trackingForm: JSON.parse(JSON.stringify(defaultTrackingForm)),
      goodsLineNamesNew:'',
      rules:{
        customerId:[{required: true, message: '请选择客户', trigger: 'change'},],
        contactId:[{required: true, message: '请选择联系人', trigger: 'change'},],
        trackingTypeId:[{required: true, message: '请选择跟进方式', trigger: 'change'},],
        trackingMethodId:[{required: true, message: '请选择沟通方式', trigger: 'change'},],
        trackingPurposeId:[{required: true, message: '请选择跟进目的', trigger: 'change'},],
        trackingContent:[{required: true, message: '请填写跟进内容', trigger: 'blur'},],
        isInvalid:[{required: true, message: '此项必填', trigger: 'change'},],
        nextTrackingTime:[{required: true, message: '此项必填', trigger: 'change'},],
      },
      contactList:[],//联系人列表
      uploadToken:{
        token:'',
      },
      imgDomain: '',
      fileLoading:false,
      popType:'',
      isBuyPermission:-1,

      querySearchList:[],

      goodsMatchDegreeList:[],
      trackingMethodList:[],
      interactList:[],
      purposeList:[],
      stepList:[],
      jt:jt,
      stepName:'',
      introduce:'',
      followType:'',
      dataId:'',
      topStepList:[],
      allTracking :'',
      allVisit :'',
      tackingNum :'',
      visitNum :'',
      topPurposeList :[],
      stepId:''
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  components : {
    gjzy,
    addContacts
  },
  created() {


  },
  watch: {
    'trackingForm.trackingMethodId' (val) {
      if(val == 7) {
        this.$set(this.rules.trackingPurposeId[0], 'required', false)
        this.$set(this.rules.nextTrackingTime[0], 'required', true)
      }else {
        this.$set(this.rules.trackingPurposeId[0], 'required', true)
        this.$set(this.rules.nextTrackingTime[0], 'required', false)

      }

    }
  },
  filters: {

  },
  methods: {
    changetrackingMethodId(){
       if(this.trackingForm.trackingMethodId == 7){
          this.trackingForm.isInvalid = 0
          this.trackingForm.trackingContent = '后续再跟进'
       }else{
         this.trackingForm.isInvalid = null
         this.trackingForm.trackingContent = ''
       }

    },
      //上传文件重写
    sliderRequest(upload) {
      // 文件上传自行处理上传
      // 创建FormData对象 添加相关上传参数
      const formData = new FormData()
      // 文件对象
      formData.append('file', upload.file)
      // key 文件名处理，这样的话七牛会识别文件时什么类型
      let timestamp = new Date().getTime();
      let fileName = timestamp + upload.file.name
      formData.append('key', fileName)
      formData.append('token', this.uploadToken.token)
      // 上传文件
      axios.post("https://upload.qiniup.com", formData, {
        onUploadProgress: (event) => {
          // 监听上传进度
          this.fileLoading = true;
          event.percent = event.loaded / event.total * 100
          upload.onProgress(event)
        }
      }).then((response) => {
        if (response.status === 200) {
          let res = response.data;
          this.trackingForm.trackingPics.push(this.imgDomain + res.key)
          this.fileLoading = false;
        } else {
          this.fileLoading = false;
          this.handleAvatarError2()
        }
      }).catch((err) => {
        this.fileLoading = false;
        this.handleAvatarError2()
      })
    },
    handleAvatarError2() {
      this.$message({
        message: '上传失败',
        type: 'error'
      });
    },
    //获取客户阶段
    getCustomerStepList(){
      return customerStepList({dataId:this.dataId}).then((res)=>{
        this.topStepList = res
      })
    },
    //切换跟进方式，变化沟通方式
    changeTmId(){
      this.interactList = [];
      this.trackingForm.trackingMethodId = ''
      if(this.trackingForm.trackingTypeId){
        this.getInteractList();
      }
    },
    //切换跟进目的，变化目的说明
    changePurposeId(){
      let i = this.purposeList.findIndex((el)=>{
        return el.purposeId == this.trackingForm.trackingPurposeId
      })
      if(i!= -1){
        this.introduce = this.purposeList[i]['introduce']
      }
    },
    //跟进目的列表
    getPurposeList(){
      getPurposeListAPI({pageNum:1,pageSize: 1000,isEnable:1,stepId:this.stepId,sort:'asc'}).then((res)=>{
        this.purposeList = res.list;
      })
    },

    //跟进方式
    getTrackingMethodList(){
      getTrackingMethodListAPI({pageNum:1,pageSize: 1000,isEnable:1}).then((res)=>{
        this.trackingMethodList = res.list
        this.trackingMethodList.forEach((item) => {
          if (item.tmId == 2) {
            item.disabled = true;
          }
        })
      })
    },

    //沟通方式
    getInteractList(){
      getInteractListAPI({pageNum:1,pageSize: 1000,isEnable:1,tmId:this.trackingForm.trackingTypeId}).then((res)=>{
        this.interactList = res.list
      })
    },
    //显示跟进阶段指引
    showGj(item){
      this.$refs.gjzy.showPop(item.stepId,this.followType,this.dataId,item.type)
    },
    //画图
    draw(x,y,y2){
      document.getElementById('main').removeAttribute('_echarts_instance_')
      var chartDom = document.getElementById('main');
      var myChart = this.$echarts.init(chartDom);
      var option;
      let self = this;
      var txt1 = "预计" + self.allTracking + self.allVisit + '次拜访' + ' '+'已完成'+self.tackingNum + '次日常跟进，'+self.visitNum + '次拜访'
      let time = new Date(new Date().toLocaleDateString()).getTime()
      let length = x.length-1
      option = {
        title: {
          text: txt1,
          left: '4%',
          top: '0',
          textStyle:{
            fontSize:12
          }

        },
        grid: {
          left: '3%',
          top: '30%',
          right:'5%'
        },
        xAxis: {
          data:x,
          axisLine:{
            lineStyle: {
              color:'#999'
            },
          },
          axisLabel: {
            color:'#000',
            showMaxLabel:true,
            formatter: function (value, index) {
              var txt = "当前进度"
              if(value*1000 == time){
                return "{jt|}\n" + txt
              }else if(index == 0 || index == length) {
                // console.log("index",index)
                return `{a|${formatDate(new Date(value * 1000), 'MM-dd')}}`
              }
            },
            rich: {
              a: {
                color: '#000',
                fontSize: '8px',
              },
              jt: {
                height: 20,
                align: 'center',
                fontSize: '8px',
                backgroundColor: {
                  image: self.jt
                }
              },
            },
          },
        },
        yAxis: {
          axisLine:{
            show:true,
            lineStyle: {
              color:'#999'
            },
          },
          axisTick:{
            show:false
          },
          axisLabel: {
            show:false
          },
          splitLine:{
            show:false
          },
        },
        series: [
          {
            name: '拜访',
            data: y2,
            type: 'scatter',
            emphasis: {
              focus: 'series',
            },
            symbol:'rect',
            itemStyle: {
              color: new this.$echarts.graphic.RadialGradient(0.4, 0.3, 1, [
                {
                  offset: 0,
                  color: 'rgb(251, 118, 123)'
                },
                {
                  offset: 1,
                  color: 'rgb(204, 46, 72)'
                }
              ])
            }
          },
          {
            name: '日常跟进',
            data: y,
            type: 'scatter',
            emphasis: {
              focus: 'series',
            },
            itemStyle: {
              color: new this.$echarts.graphic.RadialGradient(0.4, 0.3, 1, [
                {
                  offset: 0,
                  color: 'rgb(129, 227, 238)'
                },
                {
                  offset: 1,
                  color: 'rgb(25, 183, 207)'
                }
              ])
            }
          }
        ]
      };

      option && myChart.setOption(option);
    },
    //客户名称输入匹配
    querySearch(queryString){
      if(queryString && queryString!= ''){
        getCustomerOption({keywords:queryString,tab:'my'}).then((res)=>{
          this.querySearchList = res;
        })
      }
    },

    //显示增加联系人
    showContact(type, item) {
      if (type == 'add') {
        this.$refs.addContacts.showPop(type, this.trackingForm);
      } else if(type=='edit'){
        this.$refs.addContacts.showPop(type, item);
      }
    },

    //切换联系人
    changeContactId(){
      let item = this.contactList.find((el)=>{
        return this.trackingForm.contactId == el.contactId
      });
      this.isBuyPermission = item.isBuyPermission
    },
    //获取七牛TOKEN
    getUploadToken(){
      getQiniuToken().then((res)=>{
        this.uploadToken.token = res.token;
        this.imgDomain = res.domain
      })
    },
    //上传图片
    handleAvatarSuccess(res){
      this.trackingForm.trackingPics.push(this.imgDomain+res.key)
    },

    //删除图片
    delImg(index){
      this.trackingForm.trackingPics.splice(index,1)
    },

    //显示新增/编辑跟进
    showTracking(item, type, followType) {
      this.dialogVisible2 = true;
      this.dataId = item.dataId;
      this.popType = type;
      this.followType = followType;
      this.title2 = type == 'edit' ? '编辑跟进' : '新增跟进';
      this.trackingForm = JSON.parse(JSON.stringify(defaultTrackingForm));
      this.goodsLineNamesNew = item.goodsLineNamesNew;
      for(let key in defaultTrackingForm){
        if(key == 'isInvalid' || key == 'trackingPurposeId'){
          this.trackingForm[key] = item[key] || item[key] === 0 ? JSON.parse(JSON.stringify(item[key])) : JSON.parse(JSON.stringify(defaultTrackingForm[key]))
        }else{
          this.trackingForm[key] = item[key] ? JSON.parse(JSON.stringify(item[key])) : JSON.parse(JSON.stringify(defaultTrackingForm[key]))
        }
      }
      if (this.trackingForm.trackingPics[0] == '') {
        this.trackingForm.trackingPics=[]
      }
      this.getUploadToken();
      this.getCustomerStepList().then(()=>{
        let i = this.topStepList.findIndex((el)=>{
          return el.type == 3
        })
        if(i!=-1){
          this.stepId = this.topStepList[i]['stepId']
          customerStepDetail({dataId:this.dataId,stepId:this.topStepList[i]['stepId']}).then((res)=>{
            this.allTracking = res.allTracking;
            this.allVisit = res.allVisit;
            this.tackingNum = res.tackingNum;
            this.visitNum = res.visitNum;
            this.topPurposeList = res.purposeList;
            this.$nextTick(()=>{
              this.draw(res.x,res.y,res.y2)
            })
          })
        }
        this.getPurposeList()
        this.getTrackingMethodList();
        this.getInteractList();
      });
      switch (type){
        case 'add':
          this.getContactListData().then(()=>{
            this.trackingForm.contactId = this.contactList[0] ? this.contactList[0].contactId:''
          })
          break;
        case 'edit':
          this.getContactListData('edit');
          break;
      }
    },

    //关闭跟进弹窗
    handleClose2(){
      this.$refs.trackingForm.clearValidate();
      this.dialogVisible2 = false;
      this.btnLoading2 = false;
    },

    //提交跟进
    handleConfirm2(){
      this.$refs.trackingForm.validate((valid) => {
        if (valid) {
          this.btnLoading2 = true;
          let data = JSON.parse(JSON.stringify(this.trackingForm));
          data.trackingPics = data.trackingPics.join(",");
          let ti = this.trackingMethodList.findIndex((el)=>{
            return el.tmId == data.trackingTypeId;
          })
          let mi = this.interactList.findIndex((el)=>{
            return el.interactId == data.trackingMethodId;
          })

          if (data.trackingPurposeId != -1) {
            let pi = this.purposeList.findIndex((el)=>{
              return el.purposeId == data.trackingPurposeId;
            })
            data.trackingPurposeValue =  this.purposeList[pi] ? this.purposeList[pi]['purposeTitle'] :''
          }else{
            data.trackingPurposeValue = '公司破产或已关闭'
          }

          // console.log("ti",ti)
          // console.log("mi",mi)
          data.trackingTypeValue =  this.trackingMethodList[ti]['trackingMethod']
          data.trackingMethodValue = this.interactList[mi]['interactType']

          data.dataId = this.dataId
          delete data.dealComparePrice
          delete data.dealPayMethod
          addOrUpdateTracking(data).then((res)=>{
            this.btnLoading2 = false;
            this.handleClose2();
            this.$emit('getList');
            this.$message.success('操作成功！')
          }).catch(()=>{
            this.btnLoading2 = false;
          })
        }
      })
    },

    //获取联系人列表
    getContactListData(type){
      return  getContactList({customerId:this.trackingForm.customerId}).then((res)=>{
        this.contactList = res;
      })
    },

  },
}
</script>

<style  lang="scss">
.chceckspan{
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-right: 20px;
  box-sizing: border-box;
  margin:5px;
  cursor: default;
  .el-tag__close{
    float: right;
    margin-top: -17px;
    margin-right: -15px;
  }
}
.chceckspan.chceckspan2 .el-tag__close{
  margin-top: 0;
}
.avatar-uploader{
  margin-bottom:10px;
  display: inline-block;
  width:80px;
  height:80px;
  border:1px solid #DCDFE6;
  text-align: center;
  line-height: 80px;
  vertical-align: middle;
}
.check-item{
  overflow: hidden;
  margin-bottom:5px;
  .el-checkbox{
    float:left;
    line-height: 20px;
  }
  .el-checkbox__label{
    display: none;
  }
  .label{
    float:left;
    width:calc(100% - 30px);
    margin-left:10px;
    line-height: 20px;
    font-size: 12px;
  }
}
.target-div{
  height:24px;
  width:100%;
  position: relative;
  .target-line{
    position: absolute;
    width:100%;
    height:2px;
    background: #dcdfe6;
    top:50%;
    margin-top:-1px;
    z-index: 0;
  }
  .target-list{
    width:100%;
    height:24px;
    display: flex;
    justify-content:space-between;
    align-items: center;
    z-index: 1;
    position: relative;
    .target-item{
      width:24px;
      height:24px;
      border-radius: 50%;
      background: rgb(192,196,204);
      text-align: center;
      line-height: 24px;
      color:#fff;
      font-size: 12px;
    }
  }
}
</style>
